package org.jsola.contract.web;

import org.jsola.common.DateKit8;
import org.jsola.common.StrKit;
import org.jsola.contract.constant.ContractConstants;
import org.jsola.contract.constant.SignMethod;
import org.jsola.contract.constant.SignType;
import org.jsola.contract.dto.CategoryAddDTO;
import org.jsola.contract.dto.CategoryBatchDTO;
import org.jsola.contract.dto.CategoryUpdateDTO;
import org.jsola.contract.dto.IssuedCategoryAddDTO;
import org.jsola.contract.entity.CategoryDO;
import org.jsola.contract.query.CategoryQuery;
import org.jsola.contract.service.ICategoryService;
import org.jsola.contract.vo.CategoryListVO;
import org.jsola.contract.vo.CategoryVO;
import org.jsola.contract.vo.ContractGroupListVO;
import org.jsola.core.Page;
import org.jsola.core.Result;
import org.jsola.exception.ParamException;
import org.jsola.user.core.TokenUser;
import org.jsola.user.core.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;
import javax.validation.Valid;


/**
 * 合同类型
 *
 * @author JanusMix
 */
@RestController("contractCategoryController")
@RequestMapping(ContractConstants.API_PATH + "/v1/categories")
public class CategoryController implements ICategoryControllerAPI {

    @Autowired
    private ICategoryService categoryService;

    @Override
    @PostMapping
    public Result<CategoryVO> save(@Valid @RequestBody CategoryAddDTO categoryAddDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增合同类型权限校验

        return Result.success(
                categoryService.save(categoryAddDTO, tokenUser)
        );
    }


    @Override
    @PutMapping
    public Result<Integer> update(@Valid @RequestBody CategoryUpdateDTO categoryUpdateDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 修改合同类型权限校验

        int count = categoryService.update(categoryUpdateDTO, tokenUser);
        if (count == 0) {
            throw new ParamException("更新失败，请刷新页面后重试");
        }
        return Result.success(count);
    }


    @Override
    @PostMapping(value = "/batch")
    public Result batch(@Valid @RequestBody CategoryBatchDTO categoryBatchDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 批量操作权限校验

        // 批量操作，注意校验，有越权风险
        // 新增
        List<CategoryAddDTO> categoryAddDTOList = categoryBatchDTO.getCategoryAddDTOList();
        if (!CollectionUtils.isEmpty(categoryAddDTOList)) {
            categoryService.batchSave(categoryAddDTOList, tokenUser);
        }
        // 修改
        List<CategoryUpdateDTO> categoryUpdateDTOList = categoryBatchDTO.getCategoryUpdateDTOList();
        if (!CollectionUtils.isEmpty(categoryUpdateDTOList)) {
            categoryUpdateDTOList.parallelStream().forEach(
                    categoryUpdateDTO -> {
                        categoryService.update(categoryUpdateDTO, tokenUser);
                    }
            );
        }
        // 删除
        List<Long> deleteCategoryIdList = categoryBatchDTO.getDeleteCategoryIdList();
        if (!CollectionUtils.isEmpty(deleteCategoryIdList)) {
            categoryService.deleteByIds(tokenUser, deleteCategoryIdList.toArray(new Long[0]));
        }
        return Result.success();
    }


    @Override
    @DeleteMapping(value = "/{categoryId}")
    public Result<Integer> delete(@PathVariable Long categoryId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 彻底删除合同类型权限校验

        int count = categoryService.deleteByIds(tokenUser, categoryId);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @DeleteMapping
    public Result<Integer> deleteBatch(@RequestBody Long[] categoryIds) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 批量彻底删除合同类型权限校验

        int count = categoryService.deleteByIds(tokenUser, categoryIds);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @GetMapping(value = "/{categoryId}")
    public Result<CategoryVO> findById(@PathVariable Long categoryId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看合同类型权限校验

        return Result.success(
                categoryService.selectById(categoryId, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping(value = "/listAll")
    public Result<List<CategoryListVO>> listAll(@Valid CategoryQuery categoryQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看合同类型权限校验
        List<CategoryListVO> categoryListVOList = categoryService.select(categoryQuery, tokenUser.getSiteId());
        categoryListVOList.forEach(categoryListVO -> categoryService.setSealVO(categoryListVO, tokenUser));
        if (categoryQuery.getIsFilterNoSeal() != null && categoryQuery.getIsFilterNoSeal()) {
            return Result.success(
                    categoryListVOList.stream().filter(item ->
                            categoryService.checkTemplate(item, tokenUser))
                            .collect(Collectors.toList())
            );
        }
        return Result.success(
                categoryListVOList
        );
    }

    @Override
    @GetMapping(value = "/selectTreeBySubjectId")
    public Result<List<ContractGroupListVO>> selectTreeBySubjectId(@Valid String subjectId, String name) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看合同类型权限校验

        return Result.success(
                categoryService.selectTreeBySubjectId(subjectId, name, tokenUser)
        );
    }


    @Override
    @GetMapping
    public Result<Page<CategoryListVO>> page(@Valid CategoryQuery categoryQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                categoryService.selectPage(categoryQuery, tokenUser.getSiteId())
        );
    }

    @Override
    @PostMapping("saveIssuedCategory")
    public Result<List<CategoryVO>> saveIssuedCategory(@Valid @RequestBody IssuedCategoryAddDTO issuedCategoryAddDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增合同类型权限校验

        return Result.success(
                categoryService.saveIssuedCategory(issuedCategoryAddDTO, tokenUser)
        );
    }

    @Override
    @GetMapping(value = "/checkTemplateByCategoryId/{categoryId}")
    public Result<String> checkTemplateByCategoryId(@PathVariable Long categoryId) {
        TokenUser tokenUser = UserContext.getUser();

        CategoryVO categoryVO = categoryService.selectById(categoryId, tokenUser.getSiteId());

        ParamException.notNull(categoryVO, "根据合同类型id没有找到合同，请刷新重试！");
        String returnStr = categoryService.checkTemplate(categoryVO, tokenUser);
        if (StrKit.isNotEmpty(returnStr)) {
            return Result.fail(returnStr, 200);
        } else {
            return Result.success("success");
        }
    }
}

